package com.five.common.utils;

import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

/**
 * @author Ywt
 */
@Component
public class MinioUtils {
    //minio客户端
    @Autowired
    private MinioClient minioClient;
    //地址
    @Value("${minio.endpoint}")
    private String endpoint;
    //桶名
    @Value("${minio.bucketName}")
    private String bucketName;

    public String upload(MultipartFile file) {
        //获取原文件名
        String fileName = file.getOriginalFilename();
        //定义新文件名
        String newFileName = "";
        if (fileName != null) {
            //新文件名
            newFileName = UUID.randomUUID()
                    + fileName.substring(fileName.lastIndexOf("."));
        }
        try {
            InputStream in = file.getInputStream();
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(bucketName)
                    //用新文件名存入
                    .object(newFileName)
                    .stream(in, in.available(), -1)
                    .contentType(file.getContentType())
                    .build());
        } catch (Exception e) {
            e.printStackTrace();
        }
        //返回访问路径
        return endpoint + "/" + bucketName + "/" + newFileName;
    }
}
